package com.cr.dataprotect.sdk;

import com.cr.dataprotect.common.MyConstants;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class DefaultSecretKeyApiImpl implements SecretKeyApi, InitializingBean {

    public static final Map<String, String> SECRET_KEY_MAP = new HashMap<>();
    /**
     * 从配置文件中读取的敏感数据加密密钥
     */
    @Value("${dataprotect.sensitive.secretkey}")
    private String sensitiveSecretKey = "";

    /**
     * 从配置文件中读取的完整性保护密钥
     */
    @Value("${dataprotect.integrity.secretkey}")
    private String integritySecretKey = "";

    @Override
    public String loadDefaultSecretKey(String type) {
        if (MapUtils.isEmpty(SECRET_KEY_MAP) || !SECRET_KEY_MAP.containsKey(type)) {
            return null;
        }
        return SECRET_KEY_MAP.get(type);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (StringUtils.isNotEmpty(sensitiveSecretKey)) {
            SECRET_KEY_MAP.put(MyConstants.SENSITIVE, sensitiveSecretKey);
        }
        if (StringUtils.isNotEmpty(integritySecretKey)) {
            SECRET_KEY_MAP.put(MyConstants.INTEGRITY, integritySecretKey);
        }
    }
}
